// pages/home.js
const util = require('../../utils/util.js')
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    seasonInfoArray: {}
  },

  tapImage: function(evt)
  {
    var id = evt.currentTarget.id;
    console.log("点击id："+id);
  },

  /**
   * 点击收藏
   */
  tapFollow: function(evt)
  {
    //console.log(evt);
    var idStr = evt.currentTarget.id;
    var seasonId = idStr.split("_")[0];
    //console.log(seasonId);
    this.onRequestUpdateFollow(seasonId);
  },

  /**
   * 请求更新收藏信息
   */
  onRequestUpdateFollow: function(seasonId){
    var state = app.globalData.followInfo[seasonId];
    if (state == 0) {
      state = 1;
    }
    else {
      state = 0;
    }
    
    wx.request({
      url: util.url + 'user_follow',
      data: {
        unionId: app.globalData.unionId,
        seasonId: seasonId,
        followType: state
      },
      success: res => {
        console.log(res);
        this.setSeasonFollowType(res.data.seasonId,res.data.followType);
        this.onRefreshFollowInfo();
      }
    })
  },

  /**
   * 刷新收藏信息
   */
  onRefreshFollowInfo: function () {
    var followInfo = app.globalData.followInfo;
    for (let i = 0; i < this.data.seasonInfoArray.length; i++)
    {
      var season = this.data.seasonInfoArray[i].season_id;
      var followType = followInfo[season];
      var isFollow = false
      if (followType != undefined && followType != 0)
        isFollow = true
      this.setData({
        ["seasonInfoArray[" + i + "].isfollow"]: isFollow
      });
    }
  },

  setSeasonFollowType: function (season_id,follow_type) {
    app.globalData.followInfo[season_id] = follow_type;
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //刷新汇总番剧
    if (app.globalData.seasonInfo) {
      this.setData({
        seasonInfoArray: app.globalData.seasonInfo
      })
    }
    else{
      app.seasonInfoCallback = res => {
        this.setData({
          seasonInfoArray: app.globalData.seasonInfo
        })
      }
    }

    //请求收藏信息
    if (app.globalData.followInfo) {
      this.onRefreshFollowInfo();
    }
    else {
      app.followInfoCallback = res => {
        this.onRefreshFollowInfo();
      }
    }
  }

})